package com.share.handler;

import com.share.common.result.ResponseResult;
import com.share.util.common.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.Serializable;

/**
 * 未登录处理器
 */
@Slf4j
@Component
public class CustomUserNotLoginAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private final AuthenticationExceptionHandler exceptionHandler;

    public CustomUserNotLoginAuthenticationEntryPoint(AuthenticationExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        // 获取异常信息
        AuthenticationExceptionHandler.AuthenticationFailureInfo failureInfo =
                exceptionHandler.getFailureInfo(authException);

        // 记录未登录访问日志
        exceptionHandler.logAuthenticationFailure(request, authException, null);

        // 构建响应结果
        ResponseResult<String> result = ResponseResult.fail(
                        failureInfo.getStatus().getCode(),
                        failureInfo.getMessage());

        // 返回响应
        ResponseUtils.result(response, result);
    }
}